﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;

namespace TimeTravel.Commons
{
    /// <summary>
    /// 文件数据模型
    /// </summary>
    public class FileItem
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 文件或目录的完整目录
        /// </summary>
        public string FullName { get; set; }

        /// <summary>
        ///  创建时间
        /// </summary>
        public DateTime CreateDate { get; set; }

        /// <summary>
        /// 是否为文件夹
        /// </summary>
        public bool IsFolder { get; set; }

        /// <summary>
        /// 文件大小
        /// </summary>
        public long Size { get; set; }

        /// <summary>
        /// 上次访问时间
        /// </summary>
        public DateTime LastAccessDate { get; set; }

        /// <summary>
        /// 上次读写时间
        /// </summary>
        public DateTime LastWriteDate { get; set; }

        /// <summary>
        /// 文件个数
        /// </summary>
        public int FileCount { get; set; }

        /// <summary>
        /// 子目录个数
        /// </summary>
        public int SubFolderCount { get; set; }
    }

    public class FileManager
    {
        #region 构造函数
        private static string strRootFolder;
        static FileManager()
        {
            strRootFolder = HttpContext.Current.Server.MapPath("~/Uploads/");
        }
        #endregion

        #region 目录管理
        /// <summary>
        /// 获取根目录
        /// </summary>
        public static string GetRootPath()
        {
            return strRootFolder;
        }

        /// <summary>
        /// 设置根目录
        /// </summary>
        public static void SetRootPath(string path)
        {
            if (!String.IsNullOrEmpty(path))
            {
                strRootFolder = path;
            }
        }

        /// <summary>
        /// 读取目录列表
        /// </summary>
        public static List<FileItem> GetDirectoryItems()
        {
            return GetDirectoryItems(strRootFolder);
        }

        /// <summary>
        /// 读取目录列表
        /// </summary>
        public static List<FileItem> GetDirectoryItems(string path)
        {
            var list = new List<FileItem>();
            string[] folders = Directory.GetDirectories(path);
            foreach (string s in folders)
            {
                var item = new FileItem();
                var di = new DirectoryInfo(s);
                item.Name = di.Name;
                item.FullName = di.FullName;
                item.CreateDate = di.CreationTime;
                item.IsFolder = true;
                list.Add(item);
            }
            return list;
        }

        #endregion

        #region 文件管理
        /// <summary>
        /// 读取文件列表
        /// </summary>
        public static List<FileItem> GetFileItems()
        {
            return GetFileItems(strRootFolder);
        }

        /// <summary>
        /// 读取文件列表
        /// </summary>
        public static List<FileItem> GetFileItems(string path)
        {
            var list = new List<FileItem>();
            string[] files = Directory.GetFiles(path);
            foreach (string s in files)
            {
                var item = new FileItem();
                var fi = new FileInfo(s);
                item.Name = fi.Name;
                item.FullName = fi.FullName;
                item.CreateDate = fi.CreationTime;
                item.IsFolder = false;
                item.Size = fi.Length;
                list.Add(item);
            }
            return list;
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        public static bool CreateFile(string filename, string path)
        {
            if (!path.EndsWith("\\")) path = path + "\\";
            try
            {
                FileStream fs = File.Create(path  + filename);
                fs.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        public static bool CreateFile(string filename, string path, byte[] contents)
        {
            if (!path.EndsWith("\\")) path = path + "\\";
            FileStream fs = null;
            try
            {
                fs = File.Create(path + filename);
                fs.Write(contents, 0, contents.Length);
                return true;
            }
            catch (Exception)
            {
                if (fs!=null)
                {
                    fs.Close();
                }
                return false;
            }
        }

        /// <summary>
        /// 读取文件
        /// </summary>
        public static string OpenText(string filePath)
        {
            using (StreamReader sr = File.OpenText(filePath))
            {
                var output = new StringBuilder();
                string rl;
                while ((rl = sr.ReadLine()) != null)
                {
                    output.Append(rl);
                }
                sr.Close();
                return output.ToString();
            }
        }

        /// <summary>
        /// 读取文件信息
        /// </summary>
        public static FileItem GetItemInfo(string path)
        {
            var item = new FileItem();
            if (Directory.Exists(path))
            {
                var di = new DirectoryInfo(path);
                item.Name = di.Name;
                item.FullName = di.FullName;
                item.CreateDate = di.CreationTime;
                item.IsFolder = true;
                item.LastAccessDate = di.LastAccessTime;
                item.LastWriteDate = di.LastWriteTime;
                item.FileCount = di.GetFiles().Length;
                item.SubFolderCount = di.GetDirectories().Length;
            }
            else
            {
                var fi = new FileInfo(path);
                item.Name = fi.Name;
                item.FullName = fi.FullName;
                item.CreateDate = fi.CreationTime;
                item.LastAccessDate = fi.LastAccessTime;
                item.LastWriteDate = fi.LastWriteTime;
                item.IsFolder = false;
                item.Size = fi.Length;
            }
            return item;
        }

        /// <summary>
        /// 写入新文件
        /// </summary>
        public static bool WriteAllText(string path, string contents)
        {
            try
            {
                File.WriteAllText(path, contents, Encoding.Unicode);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        public static bool DeleteFile(string path)
        {
            try
            {
                File.Delete(path);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 移动文件
        /// </summary>
        public static bool MoveFile(string oldPath, string newPath)
        {
            try
            {
                File.Move(oldPath, newPath);
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 文件夹

        /// <summary>
        /// 创建文件夹
        /// </summary>
        public static void CreateFolder(string name, string parentName)
        {
            var di = new DirectoryInfo(parentName);
            di.CreateSubdirectory(name);
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        public static bool DeleteFolder(string path)
        {
            try
            {
                Directory.Delete(path);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 移动文件夹
        /// </summary>
        public static bool MoveFolder(string oldPath, string newPath)
        {
            try
            {
                Directory.Move(oldPath, newPath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 复制文件夹
        /// </summary>
        public static bool CopyFolder(string source, string destination)
        {
            try
            {
                if (destination[destination.Length - 1] != Path.DirectorySeparatorChar)
                {
                    destination += Path.DirectorySeparatorChar;
                }
                if (!Directory.Exists(destination))
                {
                    Directory.CreateDirectory(destination);
                }
                string[] files = Directory.GetFileSystemEntries(source);
                foreach (string element in files)
                {
                    if (Directory.Exists(element))
                        CopyFolder(element, destination + Path.GetFileName(element));
                    else
                        File.Copy(element, destination + Path.GetFileName(element), true);
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 检测文件
        /// <summary>
        /// 判断是否为安全文件名
        /// </summary>
        /// <param name="strExtension">文件名</param>
        public static bool IsSafeName(string strExtension)
        {
            strExtension = strExtension.ToLower();
            if (strExtension.LastIndexOf(".", StringComparison.InvariantCulture) >= 0)
            {
                strExtension = strExtension.Substring(strExtension.LastIndexOf(".", StringComparison.InvariantCulture));
            }
            else
            {
                strExtension = ".txt";
            }
            string[] arrExtension = { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap", ".jpg", ".gif", ".png", ".rar", ".zip" };
            return arrExtension.Any(t => strExtension.Equals(t));
        }

        /// <summary>
        ///  判断是否为不安全文件名
        /// </summary>
        /// <param name="strExtension">文件名、文件夹名</param>
        public static bool IsUnsafeName(string strExtension)
        {
            strExtension = strExtension.ToLower();
            if (strExtension.LastIndexOf(".", StringComparison.InvariantCulture) >= 0)
            {
                strExtension = strExtension.Substring(strExtension.LastIndexOf(".", StringComparison.InvariantCulture));
            }
            else
            {
                strExtension = ".txt";
            }
            string[] arrExtension = { ".", ".asp", ".aspx", ".cs", ".net", ".dll", ".config", ".ascx", ".master", ".asmx", ".asax", ".cd", ".browser", ".rpt", ".ashx", ".xsd", ".mdf", ".resx", ".xsd" };
            return arrExtension.Any(t => strExtension.Equals(t));
        }

        /// <summary>
        ///  判断是否为可编辑文件
        /// </summary>
        /// <param name="strExtension">文件名、文件夹名</param>
        public static bool IsCanEdit(string strExtension)
        {
            strExtension = strExtension.ToLower();

            if (strExtension.LastIndexOf(".", StringComparison.InvariantCulture) >= 0)
            {
                strExtension = strExtension.Substring(strExtension.LastIndexOf(".", StringComparison.InvariantCulture));
            }
            else
            {
                strExtension = ".txt";
            }
            string[] arrExtension = { ".htm", ".html", ".txt", ".js", ".css", ".xml", ".sitemap" };
            return arrExtension.Any(t => strExtension.Equals(t));
        }
        #endregion
    }
}
